package com.swyc.osschat.Test.StreamTest.Controller;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

import com.swyc.osschat.Test.LambdaTest.Bean.Student;
import com.swyc.osschat.Test.StreamTest.Bean.Outstanding;

import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.averagingInt;
import static java.util.stream.Collectors.maxBy;

/**
 * @author zhaol@yunrong.cn
 * @version V2.1
 * @since 2.1.0 2019/8/9 16:30
 */
public class TestCaseTwo {
    public static void main(String[] args) {
        //todo reducereduce 操作可以实现从一组值中生成一个值。在上述例子中用到的 count 、 min 和 max 方法，因为常用而被纳入标准库中。事实上，这些方法都是 reduce 操作。及早求值。
        Integer reduce = Stream.of(1, 2, 3, 4).reduce(0, (acc, x) -> acc+ x);
        System.out.println(reduce);
        List<Student> students1 = Student.generateData();
        //todo 复制students1，并移除一个学生
        Outstanding ostClass1 = new Outstanding("一班", students1);
        List<Student> students2 = new ArrayList<>(students1);
        students2.remove(1);
        Outstanding ostClass2 = new Outstanding("二班", students2);
        //todo 将ostClass1、ostClass2转换为Stream
        Stream<Outstanding> classStream = Stream.of(ostClass1, ostClass2);
        Outstanding outstandingClass = biggestGroup(classStream);
        System.out.println("人数最多的班级是：" + outstandingClass.getName());
        System.out.println("一班平均年龄是：" + averageNumberOfStudent(students1));
    }
    /**
     * 获取人数最多的班级
     */
    private static Outstanding biggestGroup(Stream<Outstanding> outstandingClasses) {
        return outstandingClasses.collect(
            maxBy(comparing(ostClass -> ostClass.getList().size())))
            .orElseGet(null);
    }

    /**
     * 计算平均年龄
     */
    private static double averageNumberOfStudent(List<Student> students) {
        return students.stream().collect(averagingInt(Student::getAge));
    }
}
